# encoding:utf-8

import json
import os
import shutil
import logging
import sys
import string
import time
from optparse import OptionParser
from ReleaseZiplua import ScriptPack


TEMPLATE_AND_DIRNAME = "TEMPLATE_ANDROID_PACK"
TEMPALTE_STUDIO_DIRNAME = "TEMPLATE_ANDROIDSTUDIO_PACK"
SDF = "wq3412"
# 命令来自于cocos compile -p android -m MOD -j 4
def build_so(andpropath, build_mode="release"):
    import os
    ndk_bin = os.environ.get("NDK_ROOT") + os.sep + "ndk-build"
    jni_path = andpropath

    def get_modulepath():
        module_path = ""
        cocos_root = os.environ.get("COCOS_X_ROOT") + "/cocos2dx-x-3.16"
        sep = ""
        if sys.platform == 'win32':
            sep = ";"
        else:
            sep = ":"

        module_path += cocos_root + sep
        module_path += cocos_root + os.sep + "cocos" + sep
        module_path += cocos_root + os.sep + "external" + sep
        module_path += cocos_root + os.sep + "cocos" + os.sep + "scripting"
        return module_path

    debugmodel = "0" if build_mode == "release" else "1"
    cmd_str = "{ndk_bin} -C {jni_path} -j4 NDK_MODULE_PATH={module_paths} NDK_DEBUG={build_mode} NDK_TOOLCHAIN_VERSION=4.9"
    cmd_str = cmd_str.format(ndk_bin=ndk_bin,
                             jni_path=jni_path,
                             build_mode=debugmodel,
                             module_paths=get_modulepath())

    ret = os.system(cmd_str)
    return ret


def build_so_bycocos(andpropath, build_mode="release"):
    cmd_cocostr = "cocos compile -s {} -p android --no-apk -m {} --app-abi armeabi-v7a --compile-script 0".format(
        andpropath, build_mode)
    ret = os.system(cmd_cocostr)
    return ret

# linux windows文件路径兼容
def path_compatible(path):
    return string.replace(path, "/", os.sep)

# string 版本号替 int 版本
def strver_2int(strver):
    ret = string.split(strver, "    .")
    return str(100 * int(ret[0]) + 10 * int(ret[1]) + int(ret[2]))

# 添加文本log记录
def add_filelogger():
    rlogger = logging.getLogger()
    filehandler = logging.FileHandler(
        "andpack.log", mode="w+", encoding='utf-8')
    fileformater = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s ---> %(message)s')
    filehandler.setFormatter(fileformater)
    rlogger.addHandler(filehandler)

# 拷贝文件夹下内容
def copy_(frompath_, tarpath_, ignorefile=[], ignoredir="", ignoreext=[]):
    for item in os.listdir(frompath_):
        itemobj = os.path.join(frompath_, item)
        if os.path.isfile(itemobj):
            itemext = item.split(".")[1] if len(item.split(".")) > 1 else ""
            if ignorefile.count(item) == 0 and ignoreext.count(itemext) == 0: 
                shutil.copy(itemobj, tarpath_)
            else:
                logging.info(
                    "Copy ignore the file -->> %s" % item)

        elif os.path.isdir(itemobj):
            tardir = os.path.join(tarpath_, item)
            if not os.path.isdir(tardir):
                os.mkdir(tardir)
            copy_(itemobj, tardir)

#====================================================================================
# 参数初始化-->>default
def _init_default_parms(cls, pcfg):
    pass

# 处理平台参数-->>default
def _handle_default_parms(cls, xmlcontent, anddir):
    return xmlcontent

# 参数初始化-->>heyshell
def _init_yuenan_parms(cls, pcfg):
    pass

# 处理平台参数-->>heyshell
def _handle_yuenan_parms(cls, xmlcontent, anddir):
    return xmlcontent
#====================================================================================

# android 打包
class AndroidPack:
    global TEMPALTE_STUDIO_DIRNAME
    global TEMPLATE_AND_DIRNAME

    global _init_default_parms
    global _handle_play800_parms

    PLAT_INITPARMS_MAP = dict(
        default=_init_default_parms,
        yuenan=_init_yuenan_parms
    )

    PLAT_HANDLEPARMS_MAP = dict(
        default=_handle_default_parms,
        yuenan=_handle_yuenan_parms
    )

    '''初始化json打包的参数'''
    @classmethod
    def _initConfig(cls, jsonfile):
        try:
            f = open(jsonfile, "r+")
            pcfg = json.loads(f.read().decode('utf-8'))
            logging.info("Read the pack config...")
            logging.info(json.dumps(pcfg, sort_keys=True, indent=4))
            f.close()
        except Exception as e:
            logging.error(
                "Read file <%s> faild! Check the json is exist?", jsonfile)
            sys.exit()

        try:
            #----base
            cls._mode = pcfg["mode"]
            cls._iconpath = pcfg["iconpath"]
            cls._platform = pcfg["platform"]
            cls._appname = pcfg["appname"]

            #---sdk path
            cls._isstudio = pcfg["isstudio"]
            cls._sdkpath = pcfg["sdkpath"]
            
            #-----androidmanifest.xml
            cls._binver = pcfg["binver"]
            cls._packagename = pcfg["packagename"]

            #-----script require
            cls._lang = pcfg["language"]
            cls._resver = pcfg["resver"]
            cls._platid = pcfg["platid"]

            if pcfg.has_key("_sdk_libtree"):
                cls.__sdk_libtree = pcfg["_sdk_libtree"]            
            # init by platform
            cls.PLAT_INITPARMS_MAP[cls._platform](cls, pcfg)
            logging.info("Init json-config done!\n")

        except Exception as e:
            logging.error(
                "Check the json file <%s>! It must be something wrong!", jsonfile)
            sys.exit()

    '''初始化打包的临时路径'''
    @classmethod
    def _initTmpdir(cls):
        tmpdir = os.path.join(cls._basepath, TEMPLATE_AND_DIRNAME)
        if os.path.isdir(tmpdir):
            shutil.rmtree(tmpdir)
        os.mkdir(tmpdir)
        # copy proj.androidxxx
        anddir = os.path.join(tmpdir, "proj.android." + cls._platform)
        logging.info("Copy proj-diff from {fromp} to {top}\n".format(
            fromp=os.path.join(cls._basepath, "proj.android." + cls._platform), top=anddir))
        shutil.copytree(os.path.join(cls._basepath, "proj.android." + cls._platform),
                        anddir, symlinks=True, ignore=shutil.ignore_patterns('obj', 'obj*'))
        return anddir

    '''更改过C++ 更新so包'''
    @classmethod
    def updateSo(cls, proj, toolpath, jsonfile, mode, platname="default"):
        logging.info("Update the lib.so file...")
        cls.CLEAN_SO = os.environ.get("CLEAN_SO")
        logging.info("CLEAN_SO: %s", cls.CLEAN_SO)

        anddir = os.path.join(proj, "proj.android")
        if cls.CLEAN_SO == True:
            shutil.rmtree(os.path.join(anddir + os.sep + "obj"))

        # build so
        ret = build_so_bycocos(anddir, mode)
        if ret != 0:
            logging.error("Run ndk-build faild!")
        logging.info("copy so to build......")

        path_buildso = path_compatible(
            anddir + "/libs/armeabi-v7a/libcocos2dlua.so")
        path_saveso = path_compatible(
            toolpath + "/sdks/android/%s/libs/armeabi-v7a/libcocos2dlua.so" % platname)
        logging.info("Copy so file from <%s> to <%s>", path_buildso, path_saveso)
        shutil.copy(path_buildso, path_saveso)
        logging.info("Done!\n")

    '''资源完备后《原生》android工程处理'''
    @classmethod
    def _handleAndroid(cls, anddir, tarsdkdirs, andxml, keyfile, andversion=23, buildversion="23.0.2"):
        sdkdir = os.environ.get("ANDROID_SDK_ROOT")
        if sys.platform == 'win32':
            javacbin = path_compatible(
                os.environ.get("JAVA_HOME") + "/javac.exe")
            javacbin = os.path.dirname(
                __file__) + "\\build-tools\\jdk1.6.0_24\\bin\\javac.exe"
            java_path = os.path.dirname(
                __file__) + "\\build-tools\\jdk1.6.0_24\\bin\\java"
        else:

            javacbin = "/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/javac"
            java_path = "/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java"
            sdkdir = "/data0/tools/android-sdk-macosx"

        logging.info("sdkdir =%s", sdkdir)
        logging.info("javacbin =%s", javacbin)

        def _sdk_parms(listcont):
            if listcont == []:
                return ""
            ret = ""
            for item in listcont:
                ret += (" -S {item}%sres" % os.sep).format(item=item)
            return ret

        def _get_alljars(path):
            jarlist = []
            for item in os.listdir(path):
                if item.endswith(".jar"):
                    itemobj = os.path.join(path, item)
                    jarlist.append(itemobj)
            return ";".join(jarlist)

        def _get_javas(path):
            javalist = []

            def iterator_(path_):
                for item in os.listdir(path_):
                    itemobj = os.path.join(path_, item)
                    if os.path.isfile(itemobj):
                        if item.endswith(".java"):
                            javastr = path_ + os.sep + "*.java"
                            if javalist.count(javastr) == 0:
                                javalist.append(javastr)
                    else:
                        iterator_(itemobj)
            iterator_(path)
            return " ".join(javalist)

        genp = os.path.join(anddir, "gen")
        binp = os.path.join(anddir, "bin")
        libp = os.path.join(anddir, "libs")
        assetpp = os.path.join(anddir, "assets")
        resp = os.path.join(anddir, "res")
        srcp = os.path.join(anddir, "src")

        os.mkdir(genp)
        os.mkdir(binp)
        os.mkdir(binp + os.sep + "classes")
        if sys.platform == 'win32':
            andjar = path_compatible(
                sdkdir + "/platforms/android-%s/android.jar" % str(andversion))
            sdkjar = path_compatible(sdkdir + "/tools/lib/sdklib.jar")
            aaptbin = path_compatible(
                sdkdir + "/build-tools/%s/aapt.exe" % buildversion)
            dxbin = path_compatible(
                sdkdir + "/build-tools/%s/dx.bat" % buildversion)
            zipbin = path_compatible(
                sdkdir + "/build-tools/%s/zipalign.exe" % buildversion)
        else:
            andjar = path_compatible(
                sdkdir + "/platforms/android-%s/android.jar" % str(andversion))
            sdkjar = path_compatible(sdkdir + "/tools/lib/sdklib.jar")
            aaptbin = path_compatible(
                sdkdir + "/build-tools/%s/aapt" % buildversion)
            dxbin = path_compatible(
                sdkdir + "/build-tools/%s/dx" % buildversion)
            zipbin = path_compatible(
                sdkdir + "/build-tools/%s/zipalign" % buildversion)

        # build android
        '''=====================================================AAPT生成R.java=============================================='''
        logging.info("Pack android gen resources...")
        cmd_str = "{aapt} package -m -J {genp} --auto-add-overlay -S {gsdkres} -M {andxml} -I {andjar}"
        # build selfdir
        aaptcmd_anddirc = cmd_str.format(
            aapt=aaptbin, genp=genp, gsdkres=resp + _sdk_parms(tarsdkdirs), andxml=andxml, andjar=andjar)
        logging.info("System call-->>>\n{cmd}".format(cmd=aaptcmd_anddirc))
        ret = os.system(aaptcmd_anddirc)

        if ret != 0:
            logging.error("pack err the command is :" + aaptcmd_anddirc)
            sys.exit()
        # build tarsdkdirs
        exres_path = []
        for path in tarsdkdirs:
            # 私有属性 会在属性前面自动加上类名
            if hasattr(cls, "_AndroidPack__sdk_libtree"):
                sdkname = path.split(os.sep)[-1]
                sdkpath = path.split(sdkname)[:-1][0]
                if cls.__sdk_libtree.has_key(sdkname):
                    for dependchild in cls.__sdk_libtree[sdkname]:
                        exres_path.append(os.path.join(sdkpath, dependchild))

            aaptcmd_child = cmd_str.format(aapt=aaptbin, genp=genp, gsdkres=path + os.sep + "res" + _sdk_parms(
                exres_path), andxml=path + os.sep + "AndroidManifest.xml", andjar=andjar)
            logging.info("System call-->>>\n{cmd}".format(cmd=aaptcmd_child))
            ret = os.system(aaptcmd_child)
            if ret != 0:
                logging.error("pack err the command is :" + aaptcmd_anddirc)
                sys.exit()
        logging.info("**Pack android gen resources done!**\n\n")

        '''=====================================================编译java文件=============================================='''

        logging.info("Complie the java file to class...")
        cmd_str = "{javacbin} -nowarn -g:none -encoding utf-8 -target 1.6 -implicit:class -bootclasspath {alljar}; -d {binclasses} {tarfiles}"

        str_andjars = _get_alljars(os.path.join(anddir, "libs"))
        str_sdksjars = ""

        genpaths = _get_javas(os.path.join(anddir, "gen"))
        javapaths = genpaths + " " + _get_javas(os.path.join(anddir, "src"))

        for path in tarsdkdirs:
            str_sdksjars += _get_alljars(os.path.join(path, "libs")) + (
                ";" if tarsdkdirs.index(path) != (len(tarsdkdirs) - 1) else "")

        cmd_str = cmd_str.format(javacbin=javacbin, alljar=andjar + ";" + str_andjars +
                                 ";" + str_sdksjars, binclasses=binp + os.sep + "classes", tarfiles=javapaths)
        cmd_str = cmd_str.replace(";;;", ";")
        cmd_str = cmd_str.replace(";;", ";")

        if sys.platform != 'win32':
            cmd_str = cmd_str.replace(";", ":")
            if cmd_str.endswith(":"):
                cmd_str = cmd_str[:-1]

        logging.info("Run then command %s :\n ", cmd_str)
        ret = os.system(cmd_str)
        if ret != 0:
            logging.error("pack err the command is :" + aaptcmd_anddirc)
            sys.exit()
        logging.info("**Complie the java file to class done!**\n\n")

        '''============================dx.bat处理文件(把*.classes打包到classes.dex一个包=========================='''
        logging.info("Dx the class...")
        if str_sdksjars.find(";;") > 0:
            str_sdksjars = str_sdksjars.replace(";;", ";")
            logging.info("str_sdksjars" + str_sdksjars)

        cmd_str = "{dxbin} --dex --output={tardxfile} {binclasses} {alljar}"
        cmd_str = cmd_str.format(dxbin=dxbin, tardxfile=binp + os.sep + "classes.dex",
                                 binclasses=binp + os.sep + "classes", alljar=str_andjars + ";" + str_sdksjars)
        cmd_str = cmd_str.replace(";;;", ";")
        cmd_str = cmd_str.replace(";;", ";")
        if sys.platform != 'win32':
            cmd_str = cmd_str.replace(";", ":")
            cmd_str = cmd_str.replace(":", " ")
            if cmd_str.endswith(":"):
                cmd_str = cmd_str[:-1]

        logging.info("Run then command %s\n ", cmd_str)
        ret = os.system(cmd_str)
        if ret != 0:
            logging.error("pack err the command is :" + aaptcmd_anddirc)
            sys.exit()
        logging.info("**Dx the class done!**\n\n")

        '''========================================所有res打包到resource.ap_====================================='''
        logging.info("Create the resource.ap_ ....")
        cmd_str = "{aapt} package -a -f --auto-add-overlay -S {gsdkres} -A {assetpp} -M {andxml} -I {andjar} -F {binpath}"
        cmd_str = cmd_str.format(aapt=aaptbin, gsdkres=resp + _sdk_parms(tarsdkdirs), assetpp=assetpp,
                                 andxml=andxml, andjar=andjar, binpath=binp + os.sep + "resources.ap_")
        os.system(cmd_str)
        logging.info("**Create the resource.ap_ done!**\n\n")

        '''========================================resource.ap_+clsses.dex+assets打包apk====================================='''
        logging.info("Build the unsign apk file...")
        cmd_str = "{java_path} -classpath {sdkjar} com.android.sdklib.build.ApkBuilderMain {tmpp} -u -z {binpath} -f {classp} -rf {srcp} -rj {libp} -nf {libp}"
        cmd_str = cmd_str.format(java_path=java_path, sdkjar=sdkjar, tmpp=binp + os.sep + "build_unsign.apk", binpath=binp + os.sep +
                                 "resources.ap_", classp=binp + os.sep + "classes.dex", srcp=os.path.join(anddir, "src"), libp=os.path.join(anddir, "libs"))
        ret = os.system(cmd_str)

        if ret != 0:
            logging.error("pack err the command is :" + cmd_str)
            sys.exit()
        logging.info("**Build Success!!**\n\n")

        apkfile = path_compatible(binp + "/build_unsign.apk")

        tarfile = path_compatible(binp + "/build_sigh.apk")



        '''========================================签名APK======================================'''
        KEYPWD = "xl0000"
        KEYALIAS = "xl0000"
        logging.info("Sign the apk....")
        cmd_str = "jarsigner -keystore {keyfile} -storepass {keypwd} -keypass {keypwd} -signedjar {apkfile} {outfile} {keyalias}"
        cmd_str = cmd_str.format(keyfile=keyfile, keypwd=KEYPWD, apkfile=binp + os.sep +
                                 "build_sign.apk", outfile=binp + os.sep + "build_unsign.apk", keyalias=KEYALIAS)
        ret = os.system(cmd_str)
        if ret != 0:
            logging.error("pack err the command is :" + aaptcmd_anddirc)
            sys.exit()
        logging.info("**Sign done!Finish!**")

        '''========================================优化APK======================================'''
        logging.info("Zipalign the apk...")
        cmd_str = "{zipalignbin} -v 4 {baseapk} {ziplignapk}"
        cmd_str = cmd_str.format(zipalignbin=zipbin, baseapk=binp + os.sep +
                                 "build_sign.apk", ziplignapk=binp + os.sep + "build_sign_zipalign.apk")
        ret = os.system(cmd_str)
        if ret != 0:
            logging.error("pack err the command is :" + cmd_str)
            sys.exit()
        logging.info("**Zipalign done!Finish!**")
        return binp + os.sep + "build_sign_zipalign.apk"

    '''资源完备后《studio》android工程处理 '''
    @classmethod 
    def _handleAndroid_studio(cls, anddir, tarsdkdirs, andxml, keyfile, andversion=23, buildversion="23.0.2"):
        tmppar = path_compatible(anddir + "/../../")
    
        basestudio = os.path.join(tmppar, "proj.android-studio-{}".format(cls._platform))
        tarstudio = os.path.join(tmppar, TEMPALTE_STUDIO_DIRNAME)   
        
        if os.path.isdir(tarstudio):
            shutil.rmtree(tarstudio)
        os.mkdir(tarstudio)
        copy_(basestudio, tarstudio)
        path_app = os.path.join(tarstudio, "app")
        copy_(anddir, path_app)

        cmd_sys = "cd {} && gradle aR".format(path_app)
        os.system(cmd_sys)

        path_outapk = path_compatible(tarstudio + "/app/build/outputs/apk")
        apkfile = None
        for filename in os.listdir(path_outapk):
            if filename.endswith(".apk"):
                apkfile = os.path.join(path_outapk, filename)
                break
            
        apksign_file = apkfile.split(".")[0] + "_signed.apk"
        if (apkfile):
            return cls._handleAndroid_unsign(apkfile, apksign_file, keyfile)
        

    @classmethod
    def _handleAndroid_unsign(cls, unsighapk, signapk, keyfile, zipalign=False):
        '''========================================签名APK======================================'''
        KEYPWD = "xl0000"
        KEYALIAS = "xl0000"
        logging.info("Sign the apk....")
        cmd_str = "jarsigner -keystore {keyfile} -storepass {keypwd} -keypass {keypwd} -signedjar {outfile} {apkfile} {keyalias}"
        cmd_str = cmd_str.format(keyfile=keyfile, keypwd=KEYPWD, apkfile=unsighapk, outfile=signapk, keyalias=KEYALIAS)
        ret = os.system(cmd_str)
        if ret != 0:
            logging.error("Sign apk failed!")
            sys.exit()
        logging.info("**Sign done!Finish!**")

        '''========================================优化APK======================================'''
        ziplignapk = None
        if (zipalign):
            logging.info("Zipalign the apk...")
            ziplignapk=signapk + "align"
            cmd_str = "{zipalignbin} -v 4 {baseapk} {ziplignapk}"
            cmd_str = cmd_str.format(zipalignbin=zipbin, baseapk=signapk, ziplignapk=ziplignapk)
            ret = os.system(cmd_str)
            if ret != 0:
                logging.error("Zipalign the apk :" + cmd_str)
                sys.exit()
            logging.info("**Zipalign done!Finish!**")
        else:
            return signapk
        return ziplignapk

    '''打包执行'''
    @classmethod
    def excute(cls, basepath, toolpath, jsonfile):

        # add logger
        add_filelogger()
        cls._basepath = basepath
        cls._respath = path_compatible(basepath + "/../../")

        basedir = basepath
        resdir = cls._respath

        # add import
        from pylibs import LuaPackHot

        #=======================Step 0-Init config=======================
        jsonconfig = path_compatible(toolpath + "/config/" + jsonfile)
        logging.info("Init the json-config --->>>%s\n", jsonconfig)
        cls._initConfig(jsonconfig)

        #=======================Step 1-Copy files=======================
        '''====================================================================='''
        logging.info("Init the template proj-path for pack...\n")
        anddir = cls._initTmpdir()
        tar_assets = os.path.join(anddir, "assets")
        if not os.path.isdir(tar_assets):
            os.mkdir(tar_assets)
        #-------------libs----------------
        # libs的游戏so更新
        # 逻辑更改

        # 游戏本身 使用公用的jar文件
        # 游戏本身 使用so文件

        backup_so = ""
        plat_sodir = path_compatible(
            toolpath + "/sdks/android/%s/libs" % cls._platform)
        if os.path.isdir(plat_sodir):
            backup_so = plat_sodir
        else:
            backup_so = path_compatible(
                toolpath + "/sdks/android/default/libs")

        tar_so = os.path.join(anddir, "libs")
        logging.info("Copy the libs files from %s to %s\n", backup_so, tar_so)
        if (not cls._isstudio):
            copy_(backup_so, tar_so)
        else:
            copy_(backup_so, tar_so, ignoreext=["jar"])

        # sdk sdk的libs的so文件拷贝
        # sdk jar并不需要拷贝
        # sdk assets需要拷贝
        for path in cls._sdkpath:
            childsdkpath = path_compatible(toolpath + "/sdks/android/" + path)

            sdk_assets = path_compatible(childsdkpath + "/assets")
            copy_(sdk_assets, tar_assets)

            sdklib_so = path_compatible(childsdkpath + "/libs")
            #["armeabi", "armeabi-v7a", "mips", "x86"]
            SODIR_NAMES = ["armeabi-v7a"]
            # 现在只使用armeabi-v7a的so兼容
            if os.path.isdir(sdklib_so):
                for childname in os.listdir(sdklib_so):
                    childdir = os.path.join(sdklib_so, childname)
                    if SODIR_NAMES.count(childname) != 0:
                        copy_(childdir, os.path.join(tar_so, childname))

        #--------------src------------------
        # 游戏src代码拷贝(已经拷贝了)
        # sdk没有src代码

        #-------------assets----------------
        # 游戏res资源拷贝
        src_assets = os.path.join(resdir, "src")
        res_assets = os.path.join(tar_assets, "res")
        os.mkdir(res_assets)

        and_assets = os.path.join(
            resdir, "res_etc1") if cls._lang == "zh_CN" else os.path.join(basedir, "res_en_etc1")
        logging.info("Copy game res from %s to %s", and_assets, tar_assets)
        copy_(and_assets, res_assets)

        #config.json 
        shutil.copy(os.path.join(resdir,"config.json"), os.path.join(tar_assets,"config.json"))

        # 游戏内的script单独处理 从res里面打包生成
        ScriptPack.excute(src_assets, tar_assets, toolpath, cls, "jitc")

        # sdk assets(已经拷贝)
        # sdks/资源也拷贝到assets
        # 额外的资源暂无
        # logging.info("Copy extra assets from %s to %s\n", sdkdir_assets, tar_assets)

        #--------------res------------------
        # 游戏res拷贝（已经拷贝)
        # sdk的res拷贝(不拷贝)
        # 筛选游戏res
        tar_res = os.path.join(anddir, "res")
        rel_iconpath = path_compatible(
            toolpath + "/iconpath/%s" % cls._iconpath)
        maxicon = path_compatible(rel_iconpath + "/1024.png")
        if os.path.isfile(maxicon) == False:
            logging.error("Chk the icon is not exist!-->>%s", maxicon)
            sys.exit()
        logging.info("Auto create icons....")
        LuaPackHot.pack_icon(maxicon, tar_res, "android")

        andxml = path_compatible(anddir + "/AndroidManifest.xml")
        if cls._isstudio is not True:
            #--------------AndroidMainfest.xml---------------
            # set AndroidManifest.xml version
            fobj = open(andxml, "r")
            fret = fobj.read().decode('utf-8')
            fobjret1 = string.replace(fret, "@VERSION_INT@", strver_2int(cls._binver) + str(time.time())).replace(
                "@VERSION_STR@", cls._binver)
            fobjret2 = string.replace(fobjret1, "@PACKAGE_NAME@", cls._packagename)
            fobjret3 = cls.PLAT_HANDLEPARMS_MAP[cls._platform](
                cls, fobjret2, anddir)  # diffrent platform
            fobj.close()
            fobj2 = open(andxml, "w+")
            fobj2.write(fobjret3.encode("utf-8"))
            fobj2.close()

            #--------------string.xml---------------
            # set string.xml version    
            strxml = path_compatible(anddir + "/res/values/strings.xml")
            sobj = open(strxml, "r")
            sret = sobj.read().decode('utf-8')
            sobjret = string.replace(sret, "@APP_NAME@", cls._appname)
            sobj.close()
            sobj2 = open(strxml, "w+")
            sobj2.write(sobjret.encode("utf-8"))
            sobj2.close()

        logging.info("Done!\n")

        sys.exit()
        '''====================================================================='''

        # Step 2-处理apk文件
        '''====================================================================='''
        sdkdir = []
        for childsdk in cls._sdkpath:
            sdkdir.append(path_compatible(
                toolpath + "/sdks/android/" + childsdk))
        keyfile = path_compatible(toolpath + "/sdks/android/xlkey") 
        
        if cls._isstudio is not True:            
            # 原生的处理打包流程
            apkfile = cls._handleAndroid(anddir, sdkdir, andxml, keyfile)

        else:
            # studio gradle 处理打包流程
            apkfile = cls._handleAndroid_studio(anddir, sdkdir, andxml, keyfile)

        if (not apkfile):
            logging.error("Handle android raise failed!")
            sys.exit()
        # rename
        newname = "{platform}_{time}_{ver}_zipalign.apk".format(time=time.strftime(
            "%m%d%H%M", time.localtime()), platform=cls._platform, ver=cls._binver)
        os.rename(apkfile, os.path.join(resdir, newname))
        '''====================================================================='''
        # if sys.platform != 'win32':
        #     os.system("sh "+toolpath + "/sendToFTP.sh " + os.path.join(basedir, newname))
        #     os.system("say finish the apk pack!")


if __name__ == "__main__":

    print("======================================")
    print("=============AndroidPack==============")
    print("======================================")

    strbol = dict(true=True, false=False)

    parser = OptionParser()

    # type 1:public apk by a jsonfile
    parser.add_option("-t", "--toolpath", dest="toolpath",
                      default=None, help="Input the tools path!")
    parser.add_option("-f", "--jsonfile", dest="jsonfile", default=None,
                      help="Input the json config file for pack the apk!")
    parser.add_option("-p", "--projpath", dest="projpath",
                      default=None, help="Project base path")

    # type 2:update so by params
    parser.add_option("-s", "--andpath", dest="andpath",
                      default=None, help="Update then so file project's path")
    parser.add_option("-m", "--somode", dest="somode",
                      default="release", help="So build mode")

    (opts, args) = parser.parse_args()
    if (opts.jsonfile and opts.toolpath and opts.projpath):
        AndroidPack.excute(opts.projpath, opts.toolpath, opts.jsonfile)
    elif (opts.andpath and opts.somode and opts.toolpath and opts.jsonfile):
        AndroidPack.updateSo(opts.andpath, opts.toolpath,
                             opts.jsonfile, opts.somode)
